﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Emgu.CV;

namespace CCDTest
{
    public class CommonFun
    {
        public static PicPositionInfo Save2Local(VideoCapture _capture, string localPath)
        {
            PicPositionInfo templatePicObj = new PicPositionInfo();
            //捕获并保存当前视频流帧
            Mat frame = new Mat();
            _capture.Retrieve(frame);
            string directoryPath = Path.Combine(Application.StartupPath, localPath);
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            string filePath = Path.Combine(directoryPath, "camera_image.jpg");
            frame.Save(filePath);
            templatePicObj.pictureBox = new PictureBox() { Image = frame.ToBitmap() };
            templatePicObj.fileName = filePath;
            return templatePicObj;
        }

        public static List<PicPositionInfo> LoadTemplatePicsFromCacheFile(string filePath)
        {
            List<PicPositionInfo> templatePics = new List<PicPositionInfo>();
            if (File.Exists(filePath))
            {
                string[] lines = File.ReadAllLines(filePath);
                foreach (var line in lines)
                {
                    if (!string.IsNullOrEmpty(line))
                    {
                        templatePics.Add(new PicPositionInfo()
                        {
                            fileName = line.Split('^')[0],
                            X = int.Parse(line.Split('^')[1]),
                            Y = int.Parse(line.Split('^')[2]),
                            Width = int.Parse(line.Split('^')[3]),
                            Height = int.Parse(line.Split('^')[4]),
                        });
                    }
                }
            }
            return templatePics;
        }
        public static bool SaveTemplatePics2CacheFile(string filePath, List<PicPositionInfo> templatePics)
        {
            using (StreamWriter writer = new StreamWriter(filePath, false))
            {
                foreach (var item in templatePics)
                {
                    string content = string.Format("{0}^{1}^{2}^{3}^{4}", item.fileName, item.X, item.Y, item.Width, item.Height);
                    writer.WriteLine(content);
                }
            }
            return true;
        }
        public static bool DeleteTemplatePicsCacheFile(string filePath)
        {
            File.Delete(filePath);
            return true;
        }
    }
}
